package com.bestcem.xm.componet.sms.push.core;

import com.bestcem.xm.componet.sms.push.PushSmsProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@AllArgsConstructor
public class GetRegisterInterceptor implements Interceptor {

    private final static String SMS_COMPONENT_CODE_KEY = "SMS_COMPONENT_CODE_KEY";

    private final PushSmsCommonApi service;

    private final PushSmsProperties pushSmsProperties;

    private final RedisTemplate<String, Object> redisTemplate;

    private final ObjectMapper mapper;

    @Override
    public @NotNull Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();

        log.info("GetRegisterInterceptor enter");
        PushBaseSetting baseSetting = pushSmsProperties.getBaseSetting();
        String orgCode = baseSetting.getOrgCode();
        if (!this.redisTemplate.opsForHash().hasKey(SMS_COMPONENT_CODE_KEY, orgCode)) {
            log.error("GetRegisterInterceptor starting");
            //注册到push
            Map<String, Object> obj = new HashMap<>();
            obj.put("account", baseSetting.getAccount());
            obj.put("password", baseSetting.getPassword());
            obj.put("sign", StringUtils.hasText(baseSetting.getSign()) ? baseSetting.getSign() : "【倍市得CEM】");
            obj.put("subcode", baseSetting.getSubcode());
            obj.put("callback", baseSetting.getCallback());
            obj.put("ttype", baseSetting.getTtype() == null ? 2 : baseSetting.getTtype());
            //push自定义component_code有问题
            //obj.put("component_code", baseSetting.getOrgCode());
            Map<String, Object> registerResult = service.register(obj);
            log.error("push短信注册返回信息:{}", registerResult);
            if (!Objects.equals(0, registerResult.get("code"))) {
                log.error("push短信注册异常:{}", registerResult);
            } else {
                Map<String, Object> idmap = mapper.convertValue(registerResult.get("data"), new TypeReference<Map<String, Object>>() {
                });
                String id = idmap.get("id").toString();
                Map<String, Object> registerInfo = service.getRegisterInfo(id);
                log.error("push短信注册信息查询:{}", registerInfo);
                if (!Objects.equals(0, registerInfo.get("code"))) {
                    log.error("push短信注册信息查询异常:{}", registerInfo);
                } else {
                    Map<String, Object> registerInfomap = mapper.convertValue(registerInfo.get("data"), new TypeReference<Map<String, Object>>() {
                    });
                    String code = registerInfomap.get("code").toString();
                    this.redisTemplate.opsForHash().putIfAbsent(SMS_COMPONENT_CODE_KEY, orgCode, code);
                }
            }
            log.error("GetRegisterInterceptor end");
        }

        Object component_code = this.redisTemplate.opsForHash().get(SMS_COMPONENT_CODE_KEY, orgCode);
        Assert.notNull(component_code, "使用push平台发送短信，请先注册获取component_code");

        if (request.body() instanceof FormBody) {
            log.warn("GetRegisterInterceptor FormBody");
            // 构造新的请求表单
            FormBody.Builder builder = new FormBody.Builder();
            FormBody body = (FormBody) request.body();
            //将以前的参数添加
            for (int i = 0; i < body.size(); i++) {
                builder.add(body.encodedName(i), body.encodedValue(i));
            }
            //追加新的参数
            builder.add("component_code", component_code.toString());
            request = request.newBuilder().post(builder.build()).build();//构造新的请求体
        } else if (request.body() instanceof MultipartBody) {
            log.warn("GetRegisterInterceptor MultipartBody");
        } else {
            log.warn("GetRegisterInterceptor JsonBody");
            RequestBody requestBody = request.body();
            Buffer buffer = new Buffer();
            Assert.notNull(requestBody, "requestBody null");
            requestBody.writeTo(buffer);
            String oldParamsJson = buffer.readUtf8();

            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            Map<String, Object> map = gson.fromJson(oldParamsJson, new TypeToken<Map<String, Object>>() {
            }.getType());
            map.put("component_code", component_code);

            String newJsonParams = gson.toJson(map);
            MediaType mediaType = MediaType.get("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(newJsonParams, mediaType);
            request = request.newBuilder().post(body).build();
        }
        return chain.proceed(request);
    }
}
